﻿using Loong.Admin.Models;
using Loong.Admin.Results.Wrapping;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Reflection;

namespace Loong.Admin.Results
{
    public class AdminResultFilter : IResultFilter, ITransientDependency
    {
        private readonly IActionResultWrapperFactory _actionResultWrapperFactory;

        public AdminResultFilter(IActionResultWrapperFactory actionResultWrapperFactory)
        {
            _actionResultWrapperFactory = actionResultWrapperFactory;
        }

        public virtual void OnResultExecuting(ResultExecutingContext context)
        {
            if (!context.ActionDescriptor.IsControllerAction())
            {
                return;
            }

            var wrapResultAttribute =
                ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(
                    context.ActionDescriptor.GetMethodInfo(),
                    new WrapResultAttribute()
                );

            if (!wrapResultAttribute!.WrapOnSuccess)
            {
                return;
            }

            _actionResultWrapperFactory.CreateFor(context).Wrap(context);
        }

        public virtual void OnResultExecuted(ResultExecutedContext context)
        {
        }
    }
}
